import { useRef, useEffect, useState, useContext } from "react";
import DeleteButton from "./DeleteButton";
import Spinner from "../icons/Spinner";
import { setNewOffset, autoGrow, setNewZIndex } from "../utils";
import { updateNote } from "../request/api";
import { NoteContext } from "../context";
const NoteCard = ({ note }) => {
  const body = note.body;
  const colors = note.colors;
  const [position, setPosition] = useState(note.position);
  const [saving, setSaving] = useState(false);
  const { setSelectedNote } = useContext(NoteContext);

  const textAreaRef = useRef(null);
  const cardRef = useRef(null);
  const keyUpTimerRef = useRef(null);

  let mouseStartPos = { x: 0, y: 0 };

  useEffect(() => {
    autoGrow(textAreaRef);
    // 每次渲染的 note 放到最上面
    setNewZIndex(cardRef.current);
  }, []);

  const mouseDown = (e) => {
    if (e.target.className === "card-header") {
      setSelectedNote(note);

      mouseStartPos.x = e.clientX;
      mouseStartPos.y = e.clientY;

      setNewZIndex(cardRef.current);

      document.addEventListener("mousemove", mouseMove);
      document.addEventListener("mouseup", mouseUp);
    }
  };

  const mouseMove = (e) => {
    // 相对位置
    let mouseMoveDir = {
      x: mouseStartPos.x - e.clientX, // x > 0 向左移动
      y: mouseStartPos.y - e.clientY, // y > 0 向上移动
    };

    mouseStartPos.x = e.clientX;
    mouseStartPos.y = e.clientY;

    // 计算新位置，判断有没有越界
    const newPosition = setNewOffset(cardRef.current, mouseMoveDir);
    setPosition(newPosition);
  };

  const mouseUp = () => {
    document.removeEventListener("mousemove", mouseMove);
    document.removeEventListener("mouseup", mouseUp);

    // 保留note位置
    const newPosition = setNewOffset(cardRef.current);
    saveNote("position", newPosition);
  };

  // 更新note信息
  const saveNote = (key, value) => {
    const payload = { [key]: value };
    try {
      updateNote(note._id, payload);
    } catch (error) {
      console.error("Error updating note:", error);
    }
    setSaving(false);
  };

  // 键盘抬起 2 秒之后才保留输入文字
  const handleKeyUp = () => {
    setSaving(true);

    if (keyUpTimerRef.current) {
      clearTimeout(keyUpTimerRef.current);
    }

    keyUpTimerRef.current = setTimeout(() => {
      saveNote("body", textAreaRef.current.value);
    }, 2000);
  };

  return (
    <div
      className="card"
      ref={cardRef}
      style={{
        backgroundColor: colors.colorBody,
        top: `${position.y}px`,
        left: `${position.x}px`,
      }}
    >
      <div
        className="card-header"
        onMouseDown={mouseDown}
        style={{ backgroundColor: colors.colorHeader }}
      >
        <DeleteButton noteId={note._id} />
        {saving && (
          <div className="card-saving">
            <Spinner color={colors.colorText} />
            <span style={{ color: colors.colorText }}>Saving...</span>
          </div>
        )}
      </div>
      <div className="card-body">
        <textarea
          ref={textAreaRef}
          defaultValue={body}
          style={{ color: colors.colorText }}
          onInput={() => autoGrow(textAreaRef)}
          onFocus={() => {
            setNewZIndex(cardRef.current);
            setSelectedNote(note);
          }}
          onKeyUp={handleKeyUp}
        ></textarea>
      </div>
    </div>
  );
};
export default NoteCard;
